package host.skiree.config;

import host.skiree.domain.User;
import host.skiree.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.Collections;

public class UserRealm extends AuthorizingRealm {

    @Resource
    UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 获取当前登录的用户对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        info.addStringPermission(user.getPerms());

        System.out.println("用户"+user.getName()+"授权了 ["+user.getPerms()+"] 权限");

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 去数据库取 并验证
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userMapper.queryUserByName(userToken.getUsername());
        if (user == null) return null;
        // 密码认证
        System.out.println("用户"+user.getName()+"正在进行登录");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }

}
